package com.gzhryc.socket.netty;

import com.gzhryc.socket.SocketConfig;
import com.gzhryc.socket.SocketMessage;
import com.gzhryc.socket.SocketNode;
import com.gzhryc.socket.message.TextWebSocketMessage;

import io.netty.channel.Channel;

public class ChannelSocketNode extends SocketNode{

	final Channel mChannel;
	
	public ChannelSocketNode(Channel channel) {
		this.mChannel = channel;
	}

	@Override
	public SocketConfig getConfig() {
		return null;
	}

	@Override
	public void start() {}

	@Override
	public void startService() {}

	@Override
	public boolean isConnected() {
		return mChannel.isActive();
	}

	@Override
	public String getId() {
		return this.mChannel.id().asLongText();
	}

	@Override
	public boolean writeAndFlush(SocketMessage message) {
		if(TextWebSocketMessage.class.isInstance(message)) {
			try {
				TextWebSocketMessage temp = TextWebSocketMessage.class.cast(message);
				return mChannel.writeAndFlush(temp.getTextWebSocketFrame()).sync().isSuccess();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			try {
				return mChannel.writeAndFlush(message.getBytes()).sync().isSuccess();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public void close() {
		try {
			this.mChannel.close().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void reconnect() {
		// TODO Auto-generated method stub
		
	}
}
